import { ArrowRightOutlined, EnvironmentOutlined } from "@ant-design/icons";
import { Empty, Modal, Select, Table, message } from "antd";
import SearchPng from "@/assets/images/search.png";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { Button, Spin } from "antd";
import { SaveOutlined } from "@ant-design/icons";
import { downloadFile, post } from "@/request";
import { useLocation } from "react-router";

declare const LiteMol: any;

export default function Search() {
  const [dataSource, setDataSource] = useState<any>([]);
  const [options, setOptions] = useState<any>([]);
  const [value, setValue] = useState<any>("");
  const [loading, setLoading] = useState(false);
  const tableRef = useRef(null);
  const [open, setOpen] = useState(false);
  const [info, setInfo] = useState("");
  const [keyword, setKeyword] = useState("");
  const location: any = useLocation();
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const isSpecies = useRef("");
  const searchName = useRef("");
  const [messageApi, contextHolder] = message.useMessage();
  const [spinning, setSpinning] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [imgUrl, setImgUrl] = useState("");
  const idRef = useRef("");
  var initLoad = true;
  const baseURL = import.meta.env.VITE_BASE_URL;
  var plugin = null;

  const columns = [
    {
      title: "Data subset",
      dataIndex: "dataSubset",
      key: "dataSubset",
      width: 160,
      fixed: "left",
      sorter: true,
    },
    {
      title: "Repeats",
      dataIndex: "repeats",
      key: "repeats",
      width: 120,
      // fixed: "left",
      sorter: true,
    },
    {
      title: "DNA or RNA",
      dataIndex: "dnaOrRna",
      key: "dnaOrRna",
      width: 160,
      sorter: true,
    },
    {
      title: "Sequence",
      dataIndex: "sequence",
      key: "sequence",
      width: 120,
      sorter: true,
    },
    {
      title: "PDB ID",
      dataIndex: "pdbId",
      key: "pdbId",
      width: 120,
      sorter: true,
    },
    {
      title: "Component",
      dataIndex: "component",
      key: "component",
      width: 200,
      sorter: true,
    },
    {
      title: "Ligand name",
      dataIndex: "ligandName",
      key: "ligandName",
      width: 120,
      sorter: true,
    },
    {
      title: "Method",
      dataIndex: "method",
      key: "method",
      width: 200,
      sorter: true,
    },
    {
      title: "Commentary[Temp]",
      dataIndex: "commentaryTemp",
      key: "commentaryTemp",
      width: 120,
      sorter: true,
    },
    {
      title: "Commentary[ion]",
      dataIndex: "commentaryIon",
      key: "commentaryIon",
      width: 120,
      sorter: true,
    },
    {
      title: "PubMed ID",
      dataIndex: "pubMedId",
      key: "pubMedId",
      width: 120,
      sorter: true,
    },
  ];
  const sortParams: any = {
    ribozyme: null,
    kobs: null,
    km: null,
    kcat: null,
    kcatKm: null,
    commentaryTemp: null,
    commentaryPh: null,
    commentaryMutant: null,
    commentaryOthers: null,
    pubmedid: null,
    ribozymeSeq: null,
    substrateSeq: null,
    annotation: null,
  };

  const getOptions = (name?: string) => {
    post("/function/getRibozymeSearchType").then((res: any) => {
      !value1.current ? setValue(res[0].id) : setValue(Number(value1.current));
      setOptions([...res].map((item) => ({ value: item.id, label: item.fieldName })));
      getDataList(name, value1.current || res[0].id);
    });
  };

  const handleChange = (value: string) => {
    setValue(value);
  };

  const getDataList = (name?: string, id?: number, current1?: number, pageSize1?: number) => {
    setLoading(true);
    post("/function/getRibozymeDataList", {
      isSpecies: isSpecies.current,
      isPage: 1,
      pageStartIndex: current1 || current,
      pageSizeIndex: pageSize1 || pageSize,
      searchName: name || keyword,
      searchField: id || value,
      speciesId: idRef.current,
      sortParams,
    })
      .then((res: any) => {
        setDataSource([...res.vos.map((item: any) => ({ ...item, key: item.id }))]);
        setTotal(res.total);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const handleOk = () => {
    setOpen(false);
    if (plugin) {
      plugin.destroy();
      plugin = null;
    }
  };

  const showModel = (params: any) => {
    if (!params.stuctuieFileUrl) return messageApi.warning("The file has not been uploaded yet");
    setOpen(true);
    setInfo(baseURL + params.stuctuieFileUrl);
  };

  const useQuery = () => {
    return new URLSearchParams(location.search);
  };

  const handleChange1 = (current: any) => {};

  const exportFile = () => {
    setSpinning(true);
    downloadFile(
      "function/exportRibozymeData",
      {
        isSpecies: isSpecies.current,
        isPage: 1,
        pageStartIndex: current,
        pageSizeIndex: pageSize,
        searchName: keyword,
        searchField: value,
        speciesId: idRef.current,
      },
      "table.xlsx"
    ).finally(() => {
      setSpinning(false);
    });
  };
  const exportFile1 = () => {
    if (!selectedRowKeys.length) {
      return messageApi.open({
        type: "error",
        content: "Please select the column.",
      });
    }
    setSpinning(true);
    downloadFile(
      "function/exportRibozymeData",
      {
        isSpecies: isSpecies.current,
        isPage: 1,
        pageStartIndex: current,
        pageSizeIndex: pageSize,
        searchName: keyword,
        searchField: value,
        speciesId: idRef.current,
        exportIds: selectedRowKeys.map((item) => Number(item)).join(","),
      },
      "table.xlsx"
    ).finally(() => {
      setSpinning(false);
    });
  };

  const sortChange = (pagination: any, filters: any, sorter: any) => {
    setCurrent(pagination.current);
    setPageSize(pagination.pageSize);
    setSelectedRowKeys([]);
    for (let key in sortParams) {
      sortParams[key] = 2;
    }
    const { columnKey, field, order } = sorter;
    if (columnKey) {
      sortParams[columnKey] = order === "ascend" ? 1 : 0;
    }
    getDataList("", 0, pagination.current, pagination.pageSize);
  };

  const rowSelection = {
    onChange: (selectedRowKeys1: any, selectedRows: any[]) => {
      setSelectedRowKeys(selectedRows.map((item) => item.id));
    },
    getCheckboxProps: (record: any) => ({
      name: record.id,
    }),
    selectedRowKeys: selectedRowKeys,
  };

  const value1 = useRef("");

  useEffect(() => {
    initLoad = false;
    const query: any = useQuery();
    isSpecies.current = query.get("isSpecies");
    searchName.current = query.get("name");
    value1.current = query.get("value");
    idRef.current = query.get("id");
    // setValue(query.get("value"));
    setKeyword(searchName.current);
    getOptions(searchName.current);

    return () => {
      initLoad = true;
    };
  }, []);

  useEffect(() => {
    if (!initLoad) return;
    try {
      if (info) {
        plugin = LiteMol.Plugin.create({ target: "#litemol" });
        plugin.loadMolecule({
          id: "1tqn",
          url: info,
          format: "pdb", // default
        });
      } else {
        messageApi.warning("The file has not been uploaded yet");
      }
    } catch (e) {
      console.log("cuowu1");
    }
  }, [info]);

  const imageRef = useRef<HTMLDivElement>(null);

  const openWindow = (params: any, key: string) => {
    console.log(params, key);
    if (key === "pubMedId") {
      if (!params.pubMedIdUrl) return messageApi.warning("There is no url address for the time being");
      window.open(params.pubMedIdUrl, "_blank");
    } else {
      if (!params.pdbIdUrl) return messageApi.warning("There is no url address for the time being");
      window.open(params.pdbIdUrl, "_blank");
    }
  };

  const handleOnMouseEnter = (e: React.MouseEvent, params: any, key: string) => {
    if (key === "pubMedId") return;
    if (!params.pdbIdImage) return;
    const { clientX, clientY } = e;
    setImgUrl(params.pdbIdImage);
    if (imageRef.current) {
      imageRef.current.style.left = clientX + 10 + "px";
      imageRef.current.style.top = clientY + 10 + "px";
      imageRef.current.style.display = "block";
    }
  };

  const handleOnMouseLeave = (key: string) => {
    if (key === "pubMedId") return;
    if (imageRef.current) {
      imageRef.current.style.display = "none";
    }
  };

  return (
    <div>
      {contextHolder}
      <Spin spinning={spinning} fullscreen tip="下载中..." size="large" />
      <div
        style={{
          maxWidth: "1200px",
          background: "#fff",
          margin: "20px auto",
          display: "flex",
          gap: "10px",
          padding: "20px",
        }}
      >
        <div style={{ color: "#459af1", cursor: "pointer" }}>
          <EnvironmentOutlined />
          <span style={{ marginLeft: "10px" }}>Home</span>
        </div>
        <div>
          <ArrowRightOutlined />
        </div>
        <div>Search</div>
      </div>
      <div style={{ width: "100%", background: "#fff", padding: "20px", boxSizing: "border-box" }}>
        <div style={{ maxWidth: "1200px", margin: "0 auto" }}>
          <div style={{ fontSize: "20px", fontWeight: "700" }}>
            List of STRs data associated with the keyword "{keyword}": {total} items
          </div>
          <div style={{ marginTop: "20px" }} className="tableText1">
            Search the table:
          </div>
          <div
            className="search1"
            style={{ display: "flex", alignItems: "center", maxWidth: "1000px", marginTop: "20px" }}
          >
            <div style={{ marginRight: "20px" }} className="tableText">
              Search the table:
            </div>
            <div
              style={{
                flex: "1",
                borderRadius: "40px",
                border: "1px solid #5ea1f7",
                padding: "15px",
                display: "flex",
                alignItems: "center",
                gap: "20px",
                height: "50px",
                boxSizing: "border-box",
              }}
            >
              <div style={{ borderRight: "1px solid #000", paddingRight: "20px" }}>
                <Select
                  value={value}
                  style={{ width: "20vw", maxWidth: "200px" }}
                  options={options}
                  onChange={handleChange}
                />
              </div>
              <div style={{ flex: "1" }}>
                <input
                  value={keyword || ""}
                  style={{ width: "100%", height: "30px", border: "none", outline: "none" }}
                  type="text"
                  placeholder="Enter any string of …"
                  onChange={(e) => setKeyword(e.target.value)}
                />
              </div>
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                background: "linear-gradient(90deg, #0078f9, #56b8fb)",
                padding: "0 20px",
                gap: "5px",
                color: "#fff",
                borderRadius: "30px",
                marginLeft: "-60px",
                cursor: "pointer",
                height: "50px",
              }}
              onClick={() => {
                setSelectedRowKeys([]);
                setCurrent(1);
                getDataList("", 0, 1);
              }}
            >
              <img src={SearchPng} alt="" />
              <div className="searchText">Search</div>
            </div>
          </div>
        </div>
        <div style={{ marginTop: "20px" }}>
          <Table
            rowSelection={{ type: "checkbox", ...rowSelection }}
            ref={tableRef}
            loading={loading}
            dataSource={dataSource}
            scroll={{ x: "max-content" }}
            pagination={{
              total: total,
              current: current,
              pageSize: pageSize,
              onChange: handleChange1,
            }}
            onChange={sortChange}
          >
            {columns.map((item) =>
              item.key === "pdbId" || item.key === "pubMedId" ? (
                <Table.Column
                  title={item.title}
                  dataIndex={item.dataIndex}
                  key={item.key}
                  width={item.width}
                  fixed={(item?.fixed as any) || false}
                  sorter={item?.sorter}
                  showSorterTooltip={false}
                  render={(id, params) => {
                    return (
                      <Button
                        onMouseEnter={(e: React.MouseEvent) => handleOnMouseEnter(e, params, item.key)}
                        onMouseLeave={() => handleOnMouseLeave(item.key)}
                        color="primary"
                        variant="link"
                        onClick={() => openWindow(params, item.key)}
                      >
                        {id}
                      </Button>
                    );
                  }}
                />
              ) : (
                <Table.Column
                  title={item.title}
                  dataIndex={item.dataIndex}
                  key={item.key}
                  width={item.width}
                  fixed={(item?.fixed as any) || false}
                  sorter={item?.sorter}
                  showSorterTooltip={false}
                />
              )
            )}
            <Table.Column
              title="3D structure"
              dataIndex="id"
              key="id"
              width={200}
              align="center"
              render={(id, params) => {
                return (
                  <Button type="primary" onClick={() => showModel(params)}>
                    View
                  </Button>
                );
              }}
            />
            <Table.Column title="Description" dataIndex="description" key="description" width={300} align="center" />
          </Table>
        </div>
        <div
          style={{ display: "flex", alignItems: "center", gap: "20px", justifyContent: "flex-end", marginTop: "20px" }}
        >
          <Button size="large" type="primary" icon={<SaveOutlined />} onClick={exportFile}>
            Save Table
          </Button>
          <Button size="large" type="primary" icon={<SaveOutlined />} onClick={exportFile1}>
            Save Selected rows
          </Button>
        </div>
      </div>

      <div
        ref={imageRef}
        style={{
          position: "fixed",
          left: 0,
          top: 0,
          padding: "10px",
          backgroundColor: "#fff",
          zIndex: 999,
          display: "none",
        }}
      >
        {imgUrl ? (
          <img src={baseURL + imgUrl} style={{ width: "200px", height: "200px" }} />
        ) : (
          <Empty style={{ width: "200px", height: "200px" }} description="暂无图片" />
        )}
      </div>

      <Modal
        title="3D structure"
        closable={{ "aria-label": "Custom Close Button" }}
        open={open}
        onCancel={handleOk}
        footer={() => <div></div>}
        width={1000}
        style={{ top: "20px" }}
      >
        <div style={{ height: "777px" }}>
          {info ? (
            <div
              id="litemol"
              style={{ width: "100%", height: "480px", marginTop: "100px", position: "relative" }}
            ></div>
          ) : (
            <div style={{ width: "100%", height: "100%", display: "grid", placeContent: "center" }}>
              <Empty description="暂未上传图片" />
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
}
